package com.qiantu.phone.ui.fragment.device;

import androidx.lifecycle.LifecycleOwner;

import com.hjq.http.listener.HttpCallback;
import com.hjq.toast.ToastUtils;
import com.qiantu.api.db.LLDeviceDBManager;
import com.qiantu.api.http.LLHttpManager;
import com.qiantu.api.http.model.HttpData;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.ui.uiutil.LLDeviceUtil;
import com.qiantu.phone.widget.SwitchDeviceView;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

/**
 *    desc   : 开关设备
 */
public final class SwitchFragment extends BaseDeviceFragment {

    private SwitchDeviceView switchView;

    public static SwitchFragment newInstance() {
        SwitchFragment fragment = new SwitchFragment();
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_switch_device;
    }

    @Override
    protected void initView() {
        super.initView();
        switchView = findViewById(R.id.switch_view);
        switchView.setOnClickListener(new SwitchDeviceView.OnClickListener() {
            @Override
            public void onClick() {
                switchOperation();
            }
        });
        updateView();
    }

    private void switchOperation(){
        Map<String, Object> option = new HashMap<>();
        option.put(LLDeviceUtil.POWER, switchView.isOpen() ? 0 : 1);
        Map<String, Object> status = new HashMap<>();
        status.put(STATUS, option);
        LLHttpManager.operationDevice((LifecycleOwner) getContext(), mDevice.getDeviceSerialNo(), status, new HttpCallback<HttpData<Void>>(null) {
            @Override
            public void onStart(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).showDialog("执行中...");
                }
            }

            @Override
            public void onSucceed(HttpData<Void> result) {
//                ToastUtils.show("执行成功");
                switchView.setState(!switchView.isOpen());
                mDevice.setIsOpen(switchView.isOpen());
                LLDeviceDBManager.getInstance(getContext()).put(mDevice);
                refreshDeviceStateByLocal();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.show(R.string.exec_failure);
            }

            @Override
            public void onEnd(Call call) {
                if(getContext() != null && getContext() instanceof AppActivity){
                    ((AppActivity) getContext()).hideDialog();
                }
            }
        });
    }

    protected void updateView(){
        super.updateView();
//        if(mDevice.isIsOnline()){
            switchView.setEnabled(true);
            switchView.setState(mDevice.getIsOpen());
//        }else{
//            switchView.setEnabled(false);
//        }
    }
}